$(function () {
    // 普通聊天
    $('#generalChat').kendoChat({
        user: {
            name: sessionStorage.getItem('userName'),
            iconUrl: sessionStorage.getItem('avatar')
        },
        typingStart: function () {
            $('#generalChat').data('kendoChat').renderUserTypingIndicator($('#generalChat').data('kendoChat').getUser());
        },
        typingEnd: function () {
            $('#generalChat').data('kendoChat').clearUserTypingIndicator($('#generalChat').data('kendoChat').getUser());
        },
        post: function (e) {
            $.ajax({
                beforeSend: function () {
                    $('#generalChat').data('kendoChat').renderUserTypingIndicator({
                        id: '001',
                        name: '🌸小艾',
                        iconUrl: 'img/temp/Esmerarda.png'
                    });
                },
                type: 'post',
                data: JSON.stringify({
                    perception: {
                        inputText: {
                            text: e.text
                        }
                    },
                    userInfo: {
                        apiKey: '73e3544b57fb47e3a2545ea0b47dc474', // 请替换成自己的 Key
                        userId: 'demo'
                    }
                }),
                url: 'http://openapi.tuling123.com/openapi/api/v2',
                contentType: 'application/json; charset=UTF-8',
                dataType: 'json',
                complete: function () {
                    $('#generalChat').data('kendoChat').clearUserTypingIndicator({
                        id: kendo.guid(),
                        name: '🌸小艾',
                        iconUrl: 'img/temp/Esmerarda.png'
                    });
                },
                success: function (res) {
                    $.each(res.results, function (i, items) {
                        if (items.resultType === 'text') { // 文本
                            $('#generalChat').data('kendoChat').renderMessage(
                                {
                                    type: 'text',
                                    text: res.results[i].values.text
                                },
                                {
                                    id: kendo.guid(),
                                    name: '🌸小艾',
                                    iconUrl: 'img/temp/Esmerarda.png'
                                }
                            );
                        } else if (items.resultType === 'url') { // 链接
                            var urlTemp = kendo.template(
                                '<div class="card mt-3">' +
                                    '<div class="card-body">' +
                                        '<a class="card-link" href="#: url #" target="_blank">#: url #</a>' +
                                    '</div>' +
                                '</div>'
                            );
                            kendo.chat.registerTemplate('url_card', urlTemp);
                            $('#generalChat').data('kendoChat').renderAttachments(
                                {
                                    attachments: [{
                                        contentType: 'url_card',
                                        content: {
                                            url: res.results[i].values.url
                                        }
                                    }],
                                    attachmentLayout: 'list'
                                },
                                {
                                    id: kendo.guid(),
                                    name: '🌸小艾',
                                    iconUrl: 'img/temp/Esmerarda.png'
                                }
                            );
                        } else if (items.resultType === 'image') { // 图片
                            var imageTemp = kendo.template(
                                '<div class="text-center mt-3">' +
                                    '<img class="img-thumbnail img-fluid" src="#: image #" alt="">' +
                                '</div>'
                            );
                            kendo.chat.registerTemplate('image_card', imageTemp);
                            $('#generalChat').data('kendoChat').renderAttachments(
                                {
                                    attachments: [{
                                        contentType: 'image_card',
                                        content: {
                                            image: res.results[i].values.image
                                        }
                                    }],
                                    attachmentLayout: 'list'
                                },
                                {
                                    id: kendo.guid(),
                                    name: '🌸小艾',
                                    iconUrl: 'img/temp/Esmerarda.png'
                                }
                            );
                        } else if (items.resultType === 'news') { // 图文
                            var newsTemp = kendo.template(
                                '<div class="k-card mt-3">' +
                                    '<div class="k-card-header">' +
                                        '<h6 class="k-card-subtitle"><i class="fab fa-weibo mr-2"></i>#: source #</h6>' +
                                    '</div>' +
                                    '<img class="k-card-image" src="#: image #" alt="">' +
                                    '<div class="k-card-body">' +
                                        '<h5 class="k-card-title">#: title #</h5>' +
                                    '</div>' +
                                    '<div class="k-card-actions">' +
                                        '<a class="k-button k-flat k-primary" href="javascript:iframeWindow(\'#: source #：#: title #\', \'80%\', \'40%\', \'#: url #\');">查看详情</a>' +
                                    '</div>' +
                                '</div>'
                            );
                            kendo.chat.registerTemplate('news_card', newsTemp);
                            $('#generalChat').data('kendoChat').renderAttachments(
                                {
                                    attachments: [{
                                        contentType: 'news_card',
                                        content: {
                                            image: res.results[i].values.news[res.results[i].values.news.length - 1].icon,
                                            title: res.results[i].values.news[res.results[i].values.news.length - 1].name,
                                            source: res.results[i].values.news[res.results[i].values.news.length - 1].info,
                                            url: res.results[i].values.news[res.results[i].values.news.length - 1].detailurl
                                        }
                                    }],
                                    attachmentLayout: 'list'
                                },
                                {
                                    id: kendo.guid(),
                                    name: '🌸小艾',
                                    iconUrl: 'img/temp/Esmerarda.png'
                                }
                            );
                            $('#generalChat').data('kendoChat').renderSuggestedActions([
                                {
                                    title: '换一换',
                                    value: '再来一条新闻呗~'
                                }
                            ]);
                        }
                    });
                },
                error: function () {
                    $('#generalChat').data('kendoChat').renderMessage(
                        {
                            type: 'text',
                            text: '亲~ 由于码云使用的是HTTPS协议~ 而图灵机器人使用的是HTTP协议~ 所以想看对话效果的亲们请部署到本地开启 [ chrome.exe --disable-web-security --user-data-dir=C:\\MyChromeDevUserData ] 模式调试~ 谢谢~ ❤️'
                        },
                        {
                            id: kendo.guid(),
                            name: '🌸小艾',
                            iconUrl: 'img/temp/Esmerarda.png'
                        }
                    );
                }
            });
        },
        toolbar: {
            toggleable: true,
            buttons: [
                {
                    name: 'emoji',
                    text: '表情',
                    iconClass: 'fas fa-smile'
                },
                {
                    name: 'sendImage',
                    text: '发送图片',
                    iconClass: 'fas fa-image'
                },
                {
                    name: 'sendFile',
                    text: '发送文件',
                    iconClass: 'fas fa-file'
                },
                {
                    name: 'empty',
                    text: '清空聊天记录',
                    iconClass: 'fas fa-trash-alt'
                }
            ]
        },
        toolClick: function (e) {
            if (e.name === 'emoji') {
                divWindow('表情', 320, 'auto',
                    '<div class="row no-gutters text-center">' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">🙂</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😊</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😃</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😄</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😀</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😁</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😆</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😎</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😋</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😛</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😜</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😝</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😅</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😂</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">🤣</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😗</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😙</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😘</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😍</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">🤩</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">🤑</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😇</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">🤭</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">🤗</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😏</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😉</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">🤨</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😐</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😑</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😶</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😮</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😯</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😦</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😧</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😳</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😲</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😨</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😱</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">🙄</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😕</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">🙁</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😟</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😠</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😣</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😖</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😩</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😫</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😭</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😰</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😥</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😢</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😤</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😒</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😓</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😞</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😔</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😌</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">🤤</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😴</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😪</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😵</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">🤫</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">🤐</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">🤕</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">🤒</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😷</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">🤧</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">🤢</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">🤮</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">🤬</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">👿</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">👽</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">🤪</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😬</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">🤔</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😺</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😸</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😹</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😿</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">🙀</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😾</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😼</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😻</a></div>' +
                        '<div class="col-2 h3"><a href="javascript:;" onclick="addEmoji(this);">😽</a></div>' +
                    '</div>'
                );
            } else if (e.name === 'sendImage') {
                $('#image').click();
            } else if (e.name === 'sendFile') {
                $('#file').click();
            } else if (e.name === 'empty') {
                confirmMsg('清空确认', '你确定要清空聊天记录吗？', 'question', function () {
                    $(e.sender.view.list).empty();
                });
            }
        }
    });
    // 图片
    $('#image').kendoUpload({
        async: {
            saveUrl: 'json/upload.json'
        },
        multiple: false,
        validation: {
            allowedExtensions: ['.jpg', '.png', '.gif', '.bmp'],
            maxFileSize: 10485760
        },
        showFileList: false,
        dropZone: '#generalChat',
        success: function (e) {
            if (e.response.result === 'y') {
                if (e.operation === 'upload') {
                    var image = e.files[0].rawFile,
                        reader = new FileReader(),
                        chat = $('#generalChat').data('kendoChat');
                    reader.onloadend = function () {
                        chat.renderAttachments({
                            attachments: [{
                                contentType: 'image_card',
                                content: {
                                    image: this.result,
                                    avatar: chat.getUser().iconUrl,
                                    name: chat.getUser().name,
                                    time: kendo.toString(new Date(), 'HH:mm:ss')
                                }
                            }],
                            attachmentLayout: 'list'
                        }, chat.getUser());
                        chat.postMessage(path + e.response.data.url);
                    };
                    reader.readAsDataURL(image);
                }
            } else {
                alertMsg(e.response.msg, 'error');
            }
        }
    }).data('kendoUpload').wrapper.hide();
    var imageTemp = kendo.template(
        '<div class="k-message-group k-alt mt-3">' +
            '<img class="k-avatar" src="#: avatar #" alt="#: name #">' +
            '<div class="k-message">' +
                '<time class="k-message-time">#: time #</time>' +
                '<div class="k-bubble">' +
                    '<a href="javascript:showBigPic(\'#: image #\');">' +
                        '<img class="img-thumbnail img-fluid" src="#: image #" alt="">' +
                    '</a>' +
                '</div>' +
            '</div>' +
        '</div>'
    );
    kendo.chat.registerTemplate('image_card', imageTemp);
    // 文件
    $('#file').kendoUpload({
        async: {
            saveUrl: 'json/upload.json'
        },
        multiple: false,
        validation: {
            allowedExtensions: ['.html', '.css', '.js', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.txt', '.pdf', '.zip', '.rar', '.7z'],
            maxFileSize: 10485760
        },
        showFileList: false,
        dropZone: '#generalChat',
        success: function (e) {
            if (e.response.result === 'y') {
                if (e.operation === 'upload') {
                    var file = e.files[0],
                        chat = $('#generalChat').data('kendoChat');
                    chat.renderAttachments({
                        attachments: [{
                            contentType: 'file_card',
                            content: {
                                file: file.name,
                                ext: file.extension,
                                size: file.size,
                                url: e.response.data.url,
                                avatar: chat.getUser().iconUrl,
                                name: chat.getUser().name,
                                time: kendo.toString(new Date(), 'HH:mm:ss')
                            }
                        }],
                        attachmentLayout: 'list'
                    }, chat.getUser());
                    chat.postMessage(path + e.response.data.url);
                }
            } else {
                alertMsg(e.response.msg, 'error');
            }
        }
    }).data('kendoUpload').wrapper.hide();
    var fileTemp = kendo.template(
        '<div class="k-message-group k-alt mt-3">' +
            '<img class="k-avatar" src="#: avatar #" alt="#: name #">' +
            '<div class="k-message">' +
                '<time class="k-message-time">#: time #</time>' +
                '<div class="k-bubble">' +
                    '<div class="media">' +
                        '# if (ext === ".html" || ext === ".css" || ext === ".js") { #' +
                            '<i class="fas fa-4x fa-file-code mr-3"></i>' +
                        '# } else if (ext === ".doc" || ext === ".docx") { #' +
                            '<i class="fas fa-4x fa-file-word mr-3"></i>' +
                        '# } else if (ext === ".xls" || ext === ".xlsx") { #' +
                            '<i class="fas fa-4x fa-file-excel mr-3"></i>' +
                        '# } else if (ext === ".ppt" || ext === ".pptx") { #' +
                            '<i class="fas fa-4x fa-file-powerpoint mr-3"></i>' +
                        '# } else if (ext === ".txt") { #' +
                            '<i class="fas fa-4x fa-file-alt mr-3"></i>' +
                        '# } else if (ext === ".pdf") { #' +
                            '<i class="fas fa-4x fa-file-pdf mr-3"></i>' +
                        '# } else if (ext === ".zip" || ext === ".rar" || ext === ".7z") { #' +
                            '<i class="fas fa-4x fa-file-archive mr-3"></i>' +
                        '# } else { #' +
                            '<i class="fas fa-4x fa-file mr-3"></i>' +
                        '# } #' +
                        '<div class="media-body text-left">' +
                            '<p class="mt-1 mb-2">#: file #</p>' +
                            '<p class="mb-0">' +
                                '#: kendo.toString(size / 1024, "0.00") # KB' +
                                '<a class="k-button ml-3" href="#: path + url #" download="#: file #">下载</a>' +
                            '</p>' +
                        '</div>' +
                    '</div>' +
                '</div>' +
            '</div>' +
        '</div>'
    );
    kendo.chat.registerTemplate('file_card', fileTemp);
});

// 添加表情
function addEmoji(dom) {
    $('.window-box').data('kendoWindow').close();
    var msgInput = $('#generalChat').data('kendoChat').messageBox.input;
    $(msgInput).val($(msgInput).val() + $(dom).text());
}